package com.example.bluetoothapplication;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private BluetoothAdapter bluetoothAdapter;
    private Integer REQUEST_ENABLE_BT=1;
    private BluetoothGatt bluetoothGatt;
    private boolean mIsScanStart=false;
    private ScanSettings mScanSettings;
    private BluetoothLeScanner mLeScanner;
    private static final long SCAN_PERIOD = 10000;
    private Handler handler;
    private Button mBtScan;
    private RecyclerView recyclerView;
//    private List<Bluetoothdevice> bluelist=new ArrayList<>();
    private HashSet<BluetoothDevice> bluelist=new HashSet<>();
    //private ArrayList<Bluetoothdevice> bluelist=new ArrayList<>();
    private RecyclerAdapter adapter;
    private EditText name1,name11,name2,name22;
    private Button bt_zhuan1,bt_zhuan2;

    @Override
    protected void
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtScan=findViewById(R.id.bt_scan);
        initview();
        //点击转换
        bt_zhuan1.setOnClickListener(this);
        recyclerView=findViewById(R.id.recycleview);
        //蓝牙
        Bluetooth();
        //请求许可
        requestPermission();
        //权限检查
        // checkPermissions();
        //点击开始扫描
        btnmBtScan();
        //recyclerView布局加载器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter=new RecyclerAdapter();
        adapter.setData(bluelist);
        recyclerView.setAdapter(adapter);
    }

    private void initview() {
        name1=findViewById(R.id.et_name1);
        name11=findViewById(R.id.et_name11);
        name2=findViewById(R.id.et_name2);
        name22=findViewById(R.id.et_name22);
        bt_zhuan1=findViewById(R.id.bt_zhuan1);
        bt_zhuan2=findViewById(R.id.bt_zhuan2);
    }

    //权限检查
    private void checkPermissions() {
        List permissions=new ArrayList();
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        List permissionDeniedList=new ArrayList();

    }
    //蓝牙判断
    private void Bluetooth() {
        //是否支持BLE
        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
            Toast.makeText(this, "不支持BLE", Toast.LENGTH_SHORT).show();
            finish();
        }
        //拿到蓝牙适配
        BluetoothManager bluetoothManager= (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter=bluetoothManager.getAdapter();
        //开启蓝牙
        if(null==bluetoothAdapter ||!bluetoothAdapter.isEnabled()){
            Intent bulethooth=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(bulethooth,REQUEST_ENABLE_BT);
        }

        //判断版本号
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mLeScanner = bluetoothAdapter.getBluetoothLeScanner();//拿到getBluetoothLeScanner对象
            mScanSettings=new ScanSettings.Builder()   //用ScanSettings 配置扫描设置
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)//扫描模式
                    .setReportDelay(3000).build();//接到数据返回时间
        }

    }
    //点击开始扫描
    private void btnmBtScan() {
        mBtScan.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {
                if(!mIsScanStart){
                   // Toast.makeText(MainActivity.this,"停止扫描",Toast.LENGTH_SHORT).show();
                    mIsScanStart=true;
                    scan(true);
                    mBtScan.setText("停止扫描");
                }else {
                   // Toast.makeText(MainActivity.this,"开始扫描",Toast.LENGTH_SHORT).show();
                    mIsScanStart=false;
                    scan(false);
                    mBtScan.setText("开始扫描");
                }
            }
        });
    }
    //通过反回调函数（ScanCallack ）获取附近蓝牙状态
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void scan(boolean enable){
        if(enable){
            mLeScanner.startScan(scanCallback);
            Log.e("TAG","scanCallback");
        }else{
            mLeScanner.stopScan(scanCallback);
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
     ScanCallback scanCallback=new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //通过 BluetoothDevice device=result .getDevice
            BluetoothDevice device=result.getDevice();//获取 ScanCallack 的result 获取附近扫描设备
                //添加数据
                bluelist.add(device);
                adapter.setData(bluelist);
                adapter.notifyDataSetChanged();
        }
    };
    //请求许可
    private void requestPermission() {
        //拥有权限，直接进行操作
        if (PackageManager.PERMISSION_GRANTED ==
                ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
        } else {
            //没有权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)) {
                // 向用户*异步*显示说明-请勿阻止
                // 这个线程在等待用户的回应！用户之后
                // 看到说明，请重试以请求许可。
            } else {
                // 无需解释，我们可以请求许可。
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        0);
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // 应用程序定义的int常量。回调方法获取
                // 请求的结果。
            }
        }

    }
    //点击转换事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_zhuan1:
                int namea = Integer.parseInt(name1.getText().toString());
                String sa = Integer.toHexString(namea);
                name11.setText(sa);
                break;
            case R.id.bt_zhuan2:
                String nameb = name2.getText().toString();
                String saa = String.valueOf(Integer.valueOf(nameb));
                name22.setText(saa);
                break;
        }
    }
}
